﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;

namespace ShortUrl.Web.Tool
{
    /// <summary>
    /// 实体转换帮助类
    /// </summary>
    /// <author></author>
    public static class EntityAux
    {
        /// <summary>
        /// (ADO)DataTable转List对象 
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="table">(ADO)DataTable</param>
        /// <returns>List对象</returns>
        public static List<T> ConvertDataSetToList<T>(DataTable table)
        {
            List<T> list = new List<T>();
            PropertyInfo[] propertys = typeof(T).GetProperties();
            foreach (DataRow row in table.Rows)
            {
                T obj = Activator.CreateInstance<T>();
                foreach (DataColumn column in table.Columns)
                {
                    foreach (PropertyInfo property in propertys)
                    {
                        if (column.ColumnName.ToLower().Equals(property.Name.ToLower()))
                        {
                            if (row[column.ColumnName] != DBNull.Value)
                            {
                                property.SetValue(obj, HackType(row[column.ColumnName], property.PropertyType), null);
                            }
                            break;
                        }
                    }
                }
                list.Add(obj);
            }
            return list;
        }

        /// <summary>
        /// 类型转换(无法转换时原样返回)
        /// </summary>
        /// <param name="value">值</param>
        /// <param name="conversionType">类型</param>
        /// <returns>新类型的值</returns>
        public static object HackType(object value, Type conversionType)
        {
            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                if (value == null)
                {
                    return null;
                }

                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
            }
            try
            {
                return Convert.ChangeType(value, conversionType);
            }
            catch
            {
                return value;
            }
        }
    }
}
